<?php

namespace common\models;

use Yii;
use common\components\ActiveRecord2015;
use yii\helpers\Json;
use linslin\yii2\curl\Curl;
use yii\web\UploadedFile;

/**
 * This is the model class for table "{{%base_img}}".
 *
 * @property integer $id
 * @property string $img_url
 * @property integer $upload_time
 */
class BaseImg extends ActiveRecord2015 {

    public $file;

    /**
     * @inheritdoc
     */
    public static function tableName() {
        return '{{%base_img}}';
    }

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['upload_time'], 'integer'],
            [['img_url'], 'string', 'max' => 256],
            [['file'], 'file'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'id' => '编号',
            'img_url' => '',
            'upload_time' => '上传时间',
            'id_deleted' => '是否删除'
        ];
    }

    /**
     * 
     * @Title: uploadsImage
     * @Description:
     * @param $files e.g(['D:\wamp\test.jpg', 'D:\wamp\test.jpg'])
     * @param $dir dirname 
     * @return: json 
     * @author: sunjian
     * @date: 2015年12月4日15:04:08
     */
    public static function uploadImages($files, $dir = 'default') {
        $ret = [];
        foreach ($files as $val) {
            if (file_exists($val)) {
                $img_url = f_remote_upload($val, true, $dir);
                $base = new BaseImg();
                $base->img_url = $img_url;
                $base->save();
                $ret[] = $base->id;
            }
        }
        return Json::encode($ret);
    }

    /**
     * 
     * @Title: uploadsImage
     * @Description:
     * @param $name input's name
     * @param $dir dirname 
     * @return: json 
     * @author: sunjian
     * @date: 2015年12月23日16:17:36
     */
    public static function uploadImage($name, $dir = 'default') {
        $return = [];
        $image = new BaseImg();
        $image->file = UploadedFile::getInstanceByName($name);
     //  echo Yii::$app->basePath . '/../uploads/' . $image->getFileName();die();
        if (is_object($image->file)) {

            $file_size = $image->file->size / 1024;
//            echo $file_size;die();
            if ($file_size > 20480) {
                $return['status'] = false;
                $return['info'] = "附件文件太大，请重新提交";
                return json_encode($return);
            }
//            var_dump($image->file->type);die();
            switch ($image->file->type) {
                case "image/pjpeg":
                   
                    break;
                case "image/jpeg":
                   
                    break;
                case "image/jpg":
                   
                    break;
                case "image/x-png":
                   
                    break;
                case "image/png":
                   
                    break;
                 case "application/msword":
                   
                    break;
                case "video/mp4":
                   
                    break;
                case "application/vnd.ms-excel":
                   
                    break;
                case "text/plain":
                   
                    break;
                case "video/rmvb":
                   
                    break;
                case "video/avi":

                   break;
                case "application/octet-stream":
                   
                    break;
                default :
                    $return['status'] = false;
                    $return['info'] = "类型不正确";
                    return json_encode($return);
            }

            $allFileName = Yii::$app->basePath . '/../uploads/' . $image->getFileName();
            $res = $image->file->saveAs($allFileName);

            $img_url = f_remote_upload($allFileName, true, $dir);
//            print_r($img_url);die();
            //f_d($img_url);
            if ($img_url) {
                $return['status'] = true;
            } else {
                $return['status'] = false;
            }
            $return['info'] = $img_url;
            return json_encode($return);
        }
    }

    /**
     *
     * @Title: getImageUrlById
     * @Description:根据图片的id获取img_url
     * @return: img_url
     * @author: yulong.wang
     * @date: 2014-12-1 下午5:11:00
     */
    public static function getImageUrlById($id) {
        $re = BaseImg::findOne($id);
        if ($re) {
            $image_url = $re->attributes['img_url'];
            return $image_url;
        } else {
            return "";
        }
    }

    /**
     * 
     * @Title: getImageUrlByGoodsId
     * @Description: 根据供应商商品的id获取img_url
     * @return: unknown
     * @author: yulong.wang
     * @date: 2014-12-15 下午4:01:19
     */
    public static function getImageUrlByGoodsId($goods_id) {
        $img_url = BaseImg::findBySql("select a.img_url from dh_base_img a,dh_base_supplier_goods b where a.id=b.img_id and a.is_deleted=0 and b.status=1 and b.is_deleted=0 and b.id=" . $goods_id)->asArray()->one();
        if ($img_url) {
            return $img_url['img_url'];
        } else {
            return "";
        }
    }

    /**
     * 
     * @Title: delete
     * @Description: 删除图片记录和源文件
     * @return: unknown
     * @author: sunjian
     * @date:2015年12月4日17:15:33
     */
    public function delete() {
        $path = $this->img_url;
        $curl = new Curl();
        $data = ['path' => $path];
        $result = $curl->post(IMAGE_DEL_URL, $data, false);
        if ($result['status']) {
            parent::delete();
            return TRUE;
        } else {
            return FALSE;
        }
    }

    /**
     * 
     * @Title: getFileName
     * @Description:  获取图片
     * @return: string
     * @author: kai.gao
     * @date: 2014-11-22 下午12:09:03
     */
    protected function getFileName() {
        return $this->uuid() . '.' . $this->file->getExtension();
    }

    /**
     * 
     * @Title: uuid
     * @Description: 生成随机图片名称 
     * @return: string
     * @author: kai.gao
     * @date: 2014-11-22 下午12:08:48
     */
    protected function uuid() {
        $being_timestamp = 1206576000;
        $suffix_len = 3;
        $time = explode(' ', microtime());
        $id = ($time[1] - $being_timestamp) . sprintf('%06u', substr($time[0], 2, 6));
        if ($suffix_len > 0) {
            $id .= substr(sprintf('%010u', mt_rand()), 0, $suffix_len);
        }
        return $id;
    }

}
